import { regeneratorRuntime } from '../../utils/runtime.js'
import { checkOrder } from '../../service/public'

import {
	getSetting,
	chooseAddress,
	openSetting,
	showModal,
	showToast,
} from '../../utils/asyncWX.js'

Page({
	data: {
		address: null,
		order: {},
	},

	onShow() {
		// console.log(wx.$user.order)

		// 找到地址
		const address = wx.getStorageSync('address') || null
		if (address) {
			address.all =
				address.provinceName +
				address.cityName +
				address.countyName +
				address.detailInfo
		}

		const order = {
			name: wx.$user.order.name,
			gid: wx.$user.order.gid,
			itemId: wx.$user.order.id,
			price: wx.$user.order.price,
			count: 1,
		}
		order.allPrice = order.price * order.count
		this.setData({
			order,
		})

		this.setData({ address })
	},
	async getAddress() {
		// 优化的版本
		try {
			const res1 = await getSetting()
			const scope = res1.authSetting['scope.address']
			if (scope === false) {
				await openSetting()
			}
			const res2 = await chooseAddress()
			// 存入本地
			wx.setStorageSync('address', res2)
		} catch (error) {
			wx.showToast({
				title: '已取消',
				icon: 'none',
			})
		}
	},
	changeNode(e) {
		console.log(e.detail.value)
	},
	changeCount(e) {
		const { index } = e.currentTarget.dataset
		console.log(index)
		let count = this.data.order.count
		if (count + index < 1 || count + index > 5) {
			return
		}
		count += index
		this.data.order.count = count
		this.data.order.allPrice = count * this.data.order.price

		console.log(this.data.order)
		this.setData({
			order: this.data.order,
		})
	},
	goPay() {
		if (!this.data.address) {
			return showToast({ title: '请先设置地址后再进行提交！' })
		}
		showModal({
			title: '支付确认',
			content: `是否支付${this.data.order.allPrice}元？`,
		})
			.then((res) => {
				// console.log(this.data.order);

				checkOrder({
					...this.data.order,
					openid: wx.getStorageSync('openid') || null,
				}).then((res) => {
					if (res.data.err_code === 1000) {
						showToast({ title: '支付成功！' })

						wx.switchTab({
							url: '/pages/profile/profile',
						})
					} else {
						showToast({ title: res.data.message })
					}
				})
			})
			.catch((res) => {
				console.log('不支付了')
			})
	},
})
